'use strict'

var http = require('http')
var https = require('https')
var fs = require('fs')
var socketIo = require('socket.io')

var express = require('express')
var serveIndex = require('serve-index')

var USERCOUNT = 3

var app = express()

//设置跨域访问
app.all('*', function (req, res, next) {
    res.header('Access-Control-Allow-Origin', '*')
    res.header('Access-Control-Allow-Headers', 'X-Requested-With,X-Token,Content-Type')
    res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS')
    res.header("Access-Control-Allow-Credentials", "true")
    res.header('X-Powered-By', ' 3.2.1')
    res.header('Content-Type', 'application/json;charset=utf-8')
    next()
})

const log = (str) => { console.log('\x1b[33m%s\x1b[0m', str) }

// 设置拦截器
app.use((req, res, next) => {
    const { method, url } = req
    log(`访问日志: [${new Date()}] [${method}:${url}]`)
    next()
})

app.use(express.static('./views'))

// 直接配置路由
app.get('/index', (req, res) => {
    const view = fs.readFileSync('./views/index.html')
    res.writeHead(200, { 'Content-Type': 'text/html;charset=UTF-8' })
    res.end(view)
})

const options = {
    key: fs.readFileSync('./cert/1557605_www.learningrtc.cn.key'), //https秘钥
    cert: fs.readFileSync('./cert/1557605_www.learningrtc.cn.pem')  //https证书
}

const https_server = https.createServer(options, app)

const hostname = '0.0.0.0'
const port = 80

// 监听端口
https_server.listen(port, hostname, () => {
    console.log('\x1b[33m%s\x1b[0m', `服务运行在 https://${hostname}:${port}/`)
})

// var http_server = http.createServer(app)
// http_server.listen(80, '0.0.0.0', () => {
//     console.log('\x1b[33m%s\x1b[0m', `HTTPS服务运行在 http://${'0.0.0.0'}:${80}/`)
// })

const io = socketIo(https_server)
const onlineUsers = new Array()
const users = {}

io.sockets.on('connection', function (socket) {
    // io.sockets.emit('connection', { 'status': '正确' })

    // 新用户进来
    socket.on('new user', function (username) {
        log(`${username} 加入聊天室`)
        if (username in users) {
        } else {
            users[username] = socket
            onlineUsers.push(username)
        }
        io.sockets.emit('online users', onlineUsers)
    });

    // 转发消息
    socket.on('private message', function (from, to, msg) {
        log(`${from} 发送消息 ${msg} 给 ${to}`)
        if (to in users) {
            users[to].emit('to' + to, { from, msg })
        }
    })

    // 转发offer
    socket.on('new offer', function (from, to, offerSDP) {
        users[to].emit('accept offer', from, offerSDP)
    })

    // 转发answer
    socket.on('answer offer', function (from, to, answerSDP) {
        users[to].emit('accept answer', from, answerSDP)
    })

    // 再次转发offer
    socket.on('again offer', function (from, to, offerSDP) {
        users[to].emit('again accept offer', from, offerSDP)
    })

    // 再次转发answer
    socket.on('again answer offer', function (from, to, answerSDP) {
        users[to].emit('again accept answer', from, answerSDP)
    })

    // 转发candidate
    socket.on('new candidate', function (from, to, candidate) {
        users[to].emit('accept candidate', from, candidate)
    })

    // 连接销毁时调用
    socket.on('disconnect', function () {
        let outusername
        for (const username in users) {
            if (users[username] === socket) {
                outusername = username
                log(`${username} 退出聊天室`)
                delete users[username]
            }
        }
        const index = onlineUsers.indexOf(outusername)
        if (index !== -1) onlineUsers.splice(index, 1)

        // 通知其他用户 在线用户变更
        io.sockets.emit('online users', onlineUsers)
    })
})